RECEIVING INPUT IN C

There are various ways for recieving input in C program.

For now we will check only one way that is going to be used in our program to recieve any use input.

The scanf() function is commonly used to receive input from the user. It reads data from the standard input (usually the keyboard) and stores it in variables. For example:

 

#include <stdio.h>

int main() {
    int num;
    printf("Enter a number: ");
    scanf("%d", &num);
    printf("You entered: %d\n", num);
    return 0;
}

scanf() is a function in C programming that allows you to read input from the user or from a file. It stands for "scan formatted" and is a part of the standard input/output library (stdio.h).

Here's how scanf() works in detail:

  1. Syntax: The general syntax of the scanf() function is:
    scanf(format, &variable);
    
    • format: It specifies the format in which the data is expected to be entered. For example, %d is used for integers, %f for floating-point numbers, %c for characters, %s for strings, etc.
    • &variable: It is the memory address of the variable where the input data will be stored. The & (address-of) operator is used to get the address of the variable.
  2. Reading Input: The scanf() function waits for the user to input data and press Enter. It then tries to match the entered data with the specified format. If the input matches the format, it is stored in the corresponding variable(s); otherwise, it can cause unexpected behavior.

  3. Ignoring Whitespace: By default, scanf() skips leading whitespace (spaces, tabs, newline) characters before reading input. However, it stops reading when it encounters the first whitespace character, so it might not be suitable for reading strings containing spaces.

  4. Return Value: The scanf() function returns the number of input items successfully matched and assigned. This can be useful for error checking.

  5. Handling Newlines: After entering data and pressing Enter, a newline character (\n) is also added to the input buffer. This can cause issues when using scanf() along with other input functions. To handle this, you can include a space before the format specifier, like scanf(" %c", &ch);. This space will skip any leading whitespace characters, including newlines.

  6. Limitations: While scanf() is a convenient way to read input, it has limitations, especially when reading strings. It doesn't handle input that exceeds the size of the provided buffer, leading to buffer overflow vulnerabilities. For safer input handling, consider using fgets().